package com.turing.post.cardmanagement.impl;

import java.math.BigInteger;
import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.turing.post.cardmanagement.util.IssueCardStockDetail;
import com.turing.post.cardmanagement.util.IssueCardStockDetailDao;
import com.turing.post.cardmanagement.util.TransferInOutStockOrderDetail;
import com.turing.post.common.util.PCPSCommonDao;
import com.turing.post.util.Config;
import com.turing.post.util.GeneralDao;
import com.turing.post.util.PCPSApplicationException;

@Stateless(mappedName = "cardmanagement.impl.IssueCardStockDetailDaoImpl")
@Remote
@Local
public class IssueCardStockDetailDaoImpl implements IssueCardStockDetailDao {

	/**
	 * 实体管理器
	 * 
	 * @see javax.persistence.EntityManager
	 */
	@PersistenceContext
	protected EntityManager _em;

	private static final String grpSumSql = ""
	// 制卡入库
			+ "sum(case when t.tranType = '0' then t.orderCount else 0 end), "
			// 调拨入库
			+ "sum(case when t.tranType = '1' then t.orderCount else 0 end), "
			// 调拨出库
			+ "sum(case when t.tranType = '2' then t.orderCount else 0 end), "
			// 盘盈入库
			+ "sum(case when t.tranType = '3' then t.orderCount else 0 end), "
			// 丢失损坏出库
			+ "sum(case when t.tranType = '9' then t.orderCount else 0 end) ";

	@SuppressWarnings("unchecked")
	@Override
	public List<IssueCardStockDetail> getIssueCardStockDetailList(
			String IssueBranchNo, String batchNo, String starttime,
			String endtime, String TranType, BigInteger cardFaceId,
			String startSeqNo, String endSeqNo, Integer page) {
		int maxResult = Config.PAGE_SIZE;
		int startPosition = maxResult * page;
		String sql = "select * from IssueCardStockDetail "
				+ "where (?1 is null or IssueBranchNo=?1) "
				+ "and (?2 is null or batchNo=?2) "
				+ "and Trantime >= to_date(?3,'yyyy-mm-dd hh24:mi:ss') "
				+ "and Trantime<=to_date(?4,'yyyy-mm-dd hh24:mi:ss') "
				+ "and (?5 is null or TranType=?5) "
				+ "and (?6 is null or cardFaceId=?6) "
				+ "and (?7 is null or ?7 between cardstartseqno and cardendseqno) "
				+ "and (?8 is null or ?8 between cardstartseqno and cardendseqno) "
				+ "order by TranTime desc";
		Query query = _em.createNativeQuery(sql, IssueCardStockDetail.class);
		query.setFirstResult(startPosition);
		query.setMaxResults(maxResult);
		query.setParameter(1, IssueBranchNo);
		query.setParameter(2, batchNo);
		query.setParameter(3, starttime);
		query.setParameter(4, endtime);
		query.setParameter(5, TranType);
		query.setParameter(6, cardFaceId);
		query.setParameter(7, startSeqNo);
		query.setParameter(8, endSeqNo);

		return query.getResultList();
	}

	@Override
	public Integer getIssueCardStockDetailCount(String IssueBranchNo,
			String batchNo, String starttime, String endtime, String TranType,
			BigInteger cardFaceId, String startSeqNo, String endSeqNo) {
		String sql = "select nvl(count(*),0) from IssueCardStockDetail "
				+ "where (?1 is null or IssueBranchNo=?1) "
				+ "and (?2 is null or batchNo=?2) "
				+ "and Trantime >= to_date(?3,'yyyy-mm-dd hh24:mi:ss') "
				+ "and Trantime<=to_date(?4,'yyyy-mm-dd hh24:mi:ss') "
				+ "and (?5 is null or TranType=?5) "
				+ "and (?6 is null or cardFaceId=?6) "
				+ "and (?7 is null or ?7 between cardstartseqno and cardendseqno) "
				+ "and (?8 is null or ?8 between cardstartseqno and cardendseqno) ";

		Query query = _em.createNativeQuery(sql);
		query.setParameter(1, IssueBranchNo);
		query.setParameter(2, batchNo);
		query.setParameter(3, starttime);
		query.setParameter(4, endtime);
		query.setParameter(5, TranType);
		query.setParameter(6, cardFaceId);
		query.setParameter(7, startSeqNo);
		query.setParameter(8, endSeqNo);
		return Integer.parseInt(query.getSingleResult().toString());
	}

	@Override
	public void insert(IssueCardStockDetail IssueCardStockDetail)
			throws PCPSApplicationException {
		GeneralDao.insert(_em, IssueCardStockDetail);
	}

	/**
	 * 按日汇总某发卡商某日分支机构卡库存日结数据
	 * 
	 * @param issueCompanyNo
	 *            发卡商NO
	 * @param tranDate
	 *            帐务日期
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Object[]> sumAllIssueCardStockDaySettlementByTranDate(
			String issueCompanyNo, Date tranDate) {
		Query query = _em
				.createNativeQuery("select t.issueBranchNo, t.cardFaceId, "
						+ grpSumSql + "from IssueCardStockDetail t "
						+ "where t.issueBranchNo like ?1 and t.tranDate = ?2 "
						+ "group by t.issueBranchNo, t.cardFaceId ");
		query.setParameter(1, issueCompanyNo + "%");
		query.setParameter(2, tranDate);
		List<Object[]> obj_list = query.getResultList();
		if (obj_list == null)
			return null;
		return obj_list;
	}

	/**
	 * 根据IoOrderId,IssueBranchNo,TranDate查询明细
	 * 
	 * @param
	 * @return 对象
	 */
	@Override
	public IssueCardStockDetail getIssueCardStockDetailByDatil(
			BigInteger IoOrderId, String IssueBranchNo, Date TranDate) {
		String sql = "select * from IssueCardStockDetail where IoOrderId="
				+ IoOrderId + "  and TranDate = to_date('" + TranDate
				+ "','yyyy-mm-dd')" + " and IssueBranchNo='" + IssueBranchNo
				+ "'";
		Query query = _em.createNativeQuery(sql,
				TransferInOutStockOrderDetail.class);
		return (IssueCardStockDetail) query.getSingleResult();
	}

	//
	// /**
	// * 卡-5 卡库存结余表--移植到（report.impl.SaleCardStockDaySettlementDaoImpl）下
	// *
	// * @param webInput
	// * @param tranDate
	// * @return
	// */
	// @SuppressWarnings("unchecked")
	// @Override
	// public List<Object[]> getCardStockDaySettlementReportByCondition(
	// PCPSWebInput webInput, String saleBranchNo, String isSingle,
	// String startTime, String endTime) {
	// if (webInput == null || PCPSUtil.isEmpty(webInput.getOperBranchNo()))
	// return null;
	// String sqltime = "";
	// if (null != startTime)
	// sqltime += " and t.trandate >= to_date('" + startTime
	// + "','yyyy-MM-dd') ";
	// if (null != endTime) {
	// sqltime += " and t.trandate <= to_date('" + endTime
	// + "','yyyy-MM-dd') ";
	// }
	// String sqlSaleBrchNo = "";
	// if (!PCPSUtil.isEmpty(isSingle) && isSingle.equals("1")) {
	// if (!PCPSUtil.isEmpty(saleBranchNo))
	// sqlSaleBrchNo += " and t.salebranchno = '" + saleBranchNo
	// + "' ";
	// } else {
	// if (!PCPSUtil.isEmpty(saleBranchNo))
	// sqlSaleBrchNo += " and t.salebranchno like rtrim('"
	// + saleBranchNo + "','0')||'%' ";
	// }
	// String sqlIssueBrchNo = "";
	// if (!PCPSUtil.isEmpty(isSingle) && isSingle.equals("1")) {
	// if (!PCPSUtil.isEmpty(saleBranchNo))
	// sqlIssueBrchNo += " and t.issuebranchno = '" + saleBranchNo
	// + "' ";
	// } else {
	// if (!PCPSUtil.isEmpty(saleBranchNo))
	// sqlIssueBrchNo += " and t.issuebranchno like rtrim('"
	// + saleBranchNo + "','0')||'%' ";
	// }
	// String sql = "select
	// t.salebranchno,a.salebranchname,t.trandate,b.cardclassicid,b.cardclassicname,c.cardparvalue/100,"
	// +
	// "t.lastbalance,t.transferin,t.surplusin,t.transferout,t.lossdamageout,t.balance,"
	// + "(c.cardparvalue*t.balance/100)totalamount "
	// + "from SaleCardStockDaySettlement t,salebranch a,cardclassic
	// b,cardparvalue c "
	// + "where t.salebranchno=a.salebranchno "
	// + "and t.cardclassicid=b.cardclassicid(+) "
	// + "and t.cardparvalueid=c.cardparvalueid(+) "
	// + sqltime
	// + sqlSaleBrchNo
	// + "union all "
	// + "select
	// t.issuebranchno,a.issuebranchname,t.trandate,b.cardclassicid,b.cardclassicname,c.cardparvalue/100,"
	// +
	// "t.lastbalance,t.transferin,t.surplusin,t.transferout,t.lossdamageout,t.balance,"
	// + "(c.cardparvalue*t.balance/100)totalamount "
	// + "from IssueCardStockDaySettlement t,issuebranch a,cardclassic
	// b,cardparvalue c "
	// + "where t.issuebranchno=a.issuebranchno "
	// + "and t.cardclassicid=b.cardclassicid(+) "
	// + "and t.cardparvalueid=c.cardparvalueid(+) "
	// + sqltime
	// + sqlIssueBrchNo + "order by 1";
	// Query query = _em.createNativeQuery(sql);
	// List<Object[]> list = query.getResultList();
	// return list;
	// }

	@EJB(mappedName = "common.impl.PCPSCommonDaoImpl")
	private PCPSCommonDao pcpsCommonDaoImpl;

	@Override
	public void insertIssueCardStockDetailList(String issueBranchNo,
			String batchNo, String saleBranchNo, BigInteger UserId, Date date,
			BigInteger faceid, String cardseqno, String endseqno, Integer count)
			throws PCPSApplicationException {
		IssueCardStockDetail ics = new IssueCardStockDetail();
		ics.setIoOrderId(pcpsCommonDaoImpl.getUniqueIntegerKey());
		ics.setIssueBranchNo(issueBranchNo);
		ics.setTranDate(date);
		ics.setTrantime(pcpsCommonDaoImpl.getDatabaseSysTime());
		ics.setTranType("2");
		ics.setCardFaceId(faceid);
		ics.setBatchNo(batchNo);
		ics.setCardStartSeqNo(cardseqno);
		ics.setCardEndSeqNo(endseqno);
		ics.setOrderCount(count);
		ics.setOperId(UserId);
		ics.setRemark("自动销售");
		insert(ics);
	}

	@Override
	public IssueCardStockDetail getIssueCardStockDetailByCardSeqNo(
			String CardStartSeqNo, String CardEndSeqNo) {
		String sql = "select * from IssueCardStockDetail where CardStartSeqNo= ?1  and CardEndSeqNo = ?2";
		Query query = _em.createNativeQuery(sql,
				TransferInOutStockOrderDetail.class);
		query.setParameter(1, CardStartSeqNo);
		query.setParameter(2, CardEndSeqNo);
		return (IssueCardStockDetail) query.getSingleResult();
	}
}
